import { yyyymmdd } from './date';

export function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    let r = (Math.random() * 16) | 0;
    let v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

export function addProjectToSchedules(project, schedules) {
  const oneDay = 24 * 60 * 60 * 1000;

  project.gap.sort((a, b) => a - b);
  let period = Math.ceil(project.total / project.daily);
  let cnt = Number(project.gap[project.gap.length - 1]) + period;
  let startDate = new Date(project.startAt);

  for (let i = 0; i < cnt - 1; i++) {
    let curDate = new Date(startDate.getTime() + i * oneDay);
    let fmtDate = yyyymmdd(curDate);
    if (!schedules.hasOwnProperty(fmtDate)) {
      schedules[fmtDate] = {
        learn: [],
        review: [],
        learnInfo: [],
        reviewInfo: [],
      };
    }

    project.gap.forEach((g) => {
      let days = (curDate - startDate) / 86400000 + 1 - Number(g);
      if (days >= 0 && days < period) {
        for (let j = 1; j <= project.daily; j++) {
          let unit = Number(days * project.daily + j);
          if (unit > project.total) break;
          if (project.reverse === true) {
            unit = project.total + 1 - unit;
          }
          if (Number(g) === 1) {
            schedules[fmtDate].learn.push(unit);
          } else {
            schedules[fmtDate].review.push(unit);
          }
        }
      }
    });
    if (schedules[fmtDate].learn.length > 0) {
      schedules[fmtDate].learnInfo.push(
        project.listName + ' ' + schedules[fmtDate].learn.sort((a, b) => a - b).join(', '),
      );
    }
    schedules[fmtDate].learn.length = 0;

    if (schedules[fmtDate].review.length > 0) {
      schedules[fmtDate].reviewInfo.push(
        project.listName + ' ' + schedules[fmtDate].review.sort((a, b) => a - b).join(', '),
      );
    }
    schedules[fmtDate].review.length = 0;
  }
}
